""" A module to support baseline-aligned xticklabels in
matplotlib. Unfortunately, the baseline-align in matplotlib seems not
supported with (usetex : True). 
"""


import matplotlib
import matplotlib.axes as maxes
import matplotlib.transforms as mtransforms

class AxesBase:
    """ Base class for an axes with baseline-aligned xticklabels. This class
    is meant to be subclasses along with matplotlib.axes. See Axes class below
    """
    def __init__(self, *kl, **kw):
        """pad size of ticklables are determined by (pad + fontsize*stretch)
        """
        
        self.__xticklabel_shift_stretch = kw.pop("xticklabel_shift_stretch", 1.)
        object.__init__(self)

    def get_xaxis_text1_transform(self, pad_points):
        
        stretch = self.__xticklabel_shift_stretch

        size = matplotlib.rcParams['xtick.labelsize']
        fontproperties=matplotlib.font_manager.FontProperties(size=size)
        font_size_points = fontproperties.get_size()*stretch

        return (self._xaxis_transform +
                mtransforms.ScaledTranslation(0, -1 * (font_size_points+pad_points) / 72.0,
                                              self.figure.dpi_scale_trans),
                "baseline", "center")



class Axes(AxesBase,
           maxes.Axes):

    def __init__(self, *kl, **kw):
        AxesBase.__init__(self, *kl, **kw)
        maxes.Axes.__init__(self, *kl, **kw)


Subplot = maxes.subplot_class_factory(Axes)


if __name__ == "__main__":

    import matplotlib.pyplot as plt
    import BaselineAlignedXticklabelsAxes

    from math import pi

    F = plt.figure(1)

    # matplotlib's axes class. xticklabels are top-aligned.
    ax1 = F.add_subplot(1, 2, 1)
    ax1.set_xticks([.5*pi, pi,1.5*pi])
    ax1.set_xticklabels([r"$\frac{1}{2} \pi$",
                         r"$\pi$",
                         r"$\frac{3}{2} \pi$"])

    # BaselineAlignedXticklabelsAxes class. xticklabels are
    # baseline-aligned.  Baseliine alignement with "usetex" enabled
    # seems not supported. It seems to give bottom-alignment instead.
    ax2 = BaselineAlignedXticklabelsAxes.Subplot(plt.gcf(), 1, 2, 2)
    F.add_subplot(ax2)
    ax2.set_xticks([.5*pi, pi, 1.5*pi])
    ax2.set_xticklabels([r"$\frac{1}{2} \pi$",
                         r"$\pi$",
                         r"$\frac{3}{2} \pi$"])

    plt.draw()
    plt.show()
    
    
    
